package com.gitee.shigen.oss.cloud;

import com.aliyun.oss.OSSClient;
import com.gitee.shigen.common.exception.BaseException;
import com.gitee.shigen.oss.config.CloudStorageConfig;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 阿里云存储
 *
 * @author shigenfu
 */
public class AliyunCloudStorageService extends CloudStorageService {

    private OSSClient client;

    public AliyunCloudStorageService(CloudStorageConfig config) {
        this.config = config;

        //初始化
        init();
    }

    private void init() {
        client = new OSSClient(config.getAliyun().getEndPoint(), config.getAliyun().getAccessKeyId(), config.getAliyun().getAccessKeySecret());
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            client.putObject(config.getAliyun().getBucketName(), path, inputStream);
        } catch (Exception e) {
            throw new BaseException("上传文件失败，请检查配置信息");
        }

        return config.getAliyun().getDomain() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getAliyun().getPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getAliyun().getPrefix(), suffix));
    }
}
